<template>
  <el-tabs :tab-position="tabPosition" style="height:750px;">
    <el-tab-pane v-for="type in types" :key="type" :label="type">
      <!-- 搜索栏 -->
      <div class="search-bar" style="display: flex; justify-content: center; margin-bottom: 20px;">
        <el-input
          :placeholder="'请输入你想搜索的 ' + type + ' 乐理知识...'"  
          v-model="queryStr[type]"
          class="input-with-select"
          style="width: 70%; max-width: 400px;"
        >
          <template #append>
            <el-button class="button" type="success" @click="queryInfo(type)">查询</el-button>
          </template>
        </el-input>
      </div>
      <!-- 乐理知识展示代码 -->
      <el-row gutter="30">
        <el-col v-for="(item, index) in filteredList[type]" :key="index" :span="5">
          <div class="theoryknowledge-out">
              <img :src="'http://localhost:8080/images/upload/' + item.cover_image" class="card-img-top" alt="乐理知识封面"
              @click="goToNotationDetail(item)">
              <div class="theoryknowledge-info">
                <h4 class="card-title">{{ item.name }}</h4>
              </div>
          </div>
        </el-col>
      </el-row>
    </el-tab-pane>
  </el-tabs>

  <el-pagination
          :current-page.sync="currentPage"
          :page-size="pageSize"
          :total="totalItems"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />

</template>
    
<script>
import axios from 'axios';

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 12,
      totalItems: 20,
      types: [
        '全部',
        '音阶与调式',
        '节奏与韵律',
        '传统记谱法',
        '曲式与结构',
        '其他'
      ],
      filteredList: {},
      imageList: [],
      queryStr: {},
      tabPosition: 'right'
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.totalItems / this.pageSize);
    }
  },
  created() {
    this.fetchTheoryKnowledgenData();
    this.initQueryStrAndFilteredList();

  },
  methods: {
    handlePageChange(page) {
      this.currentPage = page;
      this.updateFilteredList();
    },
    goToNotationDetail(theoryknowledge) {
      // 调用后端接口更新浏览量
      this.incrementViewCount(theoryknowledge.theory_knowledge_id).then(() => {
        // 更新浏览量后，再进行页面跳转
        sessionStorage.setItem('theory_knowledge_id', theoryknowledge.theory_knowledge_id);
        this.$router.push({ path: '/knowledge/' + theoryknowledge.theory_knowledge_id });
      }).catch(error => {
        console.error('浏览量更新失败：', error);
        // 即使浏览量更新失败，也进行页面跳转
        sessionStorage.setItem('theory_knowledge_id', theoryknowledge.theory_knowledge_id);
        this.$router.push({ path: '/knowledge/' + theoryknowledge.theory_knowledge_id });
      });
    },
    incrementViewCount(theoryKnowledgeId) {
      return axios.post(`/v1/tk/${theoryKnowledgeId}`).then(response => {
        console.log('View count incremented');
        return response;
      }).catch(error => {
        console.error('Failed to increment view count:', error);
        throw error;
      });
    },
    initQueryStrAndFilteredList() {
      this.types.forEach(type => {
        this.queryStr[type] = '';
        this.filteredList[type] = [];
      });
      this.filteredList['全部'] = [];
    },
    fetchTheoryKnowledgenData() {
      axios.get('/v1/tk1/').then(response => {
        this.imageList = response.data;
        this.totalItems = this.imageList.length; // 设置总条目数
        this.types.forEach(type => {
          this.filterData(type);
        });
        this.updateFilteredList();
      }).catch(error => {
        console.error('获取乐理知识数据失败：', error);
      });
    },
    filterData(type) {
      if (type === '全部') {
        this.filteredList[type] = this.imageList.slice();
      } else {
        this.filteredList[type] = this.imageList.filter(item => item.type === type);
      }
    },
    queryInfo(type) {
      if (this.queryStr[type].trim().length > 0) {
        const query = this.queryStr[type].trim();
        const matched = this.imageList.filter(item => item.name.includes(query));
        this.filteredList[type] = type === '全部' ? matched : matched.filter(item => item.type === type);
      } else {
        this.filterData(type);
      }
    },
    updateFilteredList() {
      this.types.forEach(type => {
        const filteredData = type === '全部' ? this.imageList : this.imageList.filter(item => item.type === type);
        const start = (this.currentPage - 1) * this.pageSize;
        const end = this.currentPage * this.pageSize;
        this.filteredList[type] = filteredData.slice(start, end);
      });
    },
  }
};
</script>
    
    <style>
 .input-with-select{
    width: 200px; /* 你可以根据需要调整这个值 */
    padding: 5px; /* 内边距，可以根据需要调整 */
    font-size: 16px; /* 字体大小，可以根据需要调整 */
    border: 1px solid #ffffff; /* 边框样式，可以根据需要调整 */
    border-radius: 4px; /* 边框圆角，可以根据需要调整 */
  }

  .theoryknowledge-out{
  width: 100%;
  height: 100%;
  display: flex; 
  flex-direction: column;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  overflow: hidden;
}
.el-row {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap; 
}
.el-col {
  margin-bottom: 30px; /* 每张卡片底部的间距增加 */
}
.theoryknowledge-cover{
  width: 100%;
  height: 200px; /* 固定图片的高度，确保占据卡片的上方区域 */
  object-fit: cover; /* 确保图片填充区域，不变形 */
}
.theoryknowledge-info {
  padding: 10px;
  flex-grow: 1; 
  text-align: center;
}
.theoryknowledge-info h4 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-top: 10px;
}

.theoryknowledge-info p {
  font-size: 14px;
  color: #777;
}


/* 鼠标悬浮特效 */
.theoryknowledge-out:hover {
  transform: scale(1.03); /* 轻微放大 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}
/* 确保图片宽度和高度一致 */
.card-img-top {
  width: 100%; 
  height: 120px;
  /* 图片高度固定 */
  object-fit: cover; 
}

.theoryknowledge-item {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}

    </style>